package com.yidu.boss.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author luoyushan
 */
@Configuration
public class ShiorConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityMannger") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        /**
         * anon:无需认证可以访问
         * authc:必须认证了才能访问
         * user:必须拥有记住我 功能才能用
         * role:拥有某个角色才能访问
         */
        LinkedHashMap<String, String> hashMap = new LinkedHashMap<>();
        hashMap.put("/user/*","authc");
        //为过滤器设置拦截对象
        shiroFilterFactoryBean.setFilterChainDefinitionMap(hashMap);
        //设置被拦截后跳转的页面
        shiroFilterFactoryBean.setLoginUrl("/user/login");
        //设置无权限访问页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/user/access");
        return shiroFilterFactoryBean;
    }



    //DefaultWebSecurityManager
    @Bean(name = "securityMannger")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }

    //创建realm对象 需要自定义
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

}
